package com.sensePlusVR.base;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnSystemUiVisibilityChangeListener;
import android.view.Window;
import android.view.WindowManager;

import com.sensePlusVR.main.R;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.ObjectUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author: Loren
 * @create: 2016-7-1上午10:35:18
 * @desc: Activity 基类
 *
 */
@SuppressLint("InlinedApi")
@SuppressWarnings("unused")
public abstract class BaseActivity extends AppCompatActivity {
	private final String TAG = getClass().getSimpleName();//当前的子Activity
	private final String mPageName = TAG;
	public ProgressDialog dialog;
	private Handler mHandeler;
	private static final long delay = 3000;
    private final int REQUEST_CODE_BT = 100;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyLog.d(TAG, "onCreate");
		mHandeler = new Handler(Looper.getMainLooper());
		setNavigationTrans();
		setMyContentView();
		getIntentData();
		beforeView();
		initView();
		initData();
	}

	public boolean checkBtAdminPermission(){

	    return checkPermissionisGranted(Manifest.permission.BLUETOOTH_ADMIN);
    }

    public boolean checkBtPermission(){
        return checkPermissionisGranted(Manifest.permission.BLUETOOTH) &&
                checkPermissionisGranted(Manifest.permission.ACCESS_FINE_LOCATION) &&
                checkPermissionisGranted(Manifest.permission.ACCESS_COARSE_LOCATION);
    }

	public boolean checkPermissionisGranted(String permission){
        if(this.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.M){
            return true;
        }
		if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED){
			return true;
		}else{
			return false;
		}
	}

	public void requestBtPermissions(){
        List<String> denyPermissions = new ArrayList<>();
        if (!checkPermissionisGranted(Manifest.permission.BLUETOOTH)){
            denyPermissions.add(Manifest.permission.BLUETOOTH);
            if (shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH)){
                showRequestResonForBt();
            }
        }
        if (!checkPermissionisGranted(Manifest.permission.BLUETOOTH_ADMIN)){
            denyPermissions.add(Manifest.permission.BLUETOOTH_ADMIN);
            if (shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH_ADMIN)){
                showRequestResonForBtAdmin();
            }
        }
        if (!checkPermissionisGranted(Manifest.permission.ACCESS_FINE_LOCATION)){
            denyPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)){
                showRequestResonForBt();
            }
        }
        if (!checkPermissionisGranted(Manifest.permission.ACCESS_COARSE_LOCATION)){
            denyPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)){
                showRequestResonForBt();
            }
        }
        MyLog.d(TAG, "denyPermissions="+denyPermissions);
        String [] denyp = new String[denyPermissions.size()];
        for (int i = 0; i < denyPermissions.size(); i++){
            denyp[i] = denyPermissions.get(i);
        }
        requestPermissions(denyp, REQUEST_CODE_BT);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_CODE_BT){
            for (int index = 0; index < permissions.length; index ++){
                String per = permissions[index];
                boolean granted = grantResults[index] == PackageManager.PERMISSION_GRANTED;
                if (per.equals(Manifest.permission.BLUETOOTH_ADMIN)){
                    onBlueToothAdminPermission(granted);
                }else if (per.equals(Manifest.permission.BLUETOOTH) ||
                        per.equals(Manifest.permission.ACCESS_COARSE_LOCATION) ||
                        per.equals(Manifest.permission.ACCESS_FINE_LOCATION)){
                    onBlueToothPermission(granted);
                }
            }
        }
    }


    public void onBlueToothPermission(boolean granted){

    }
    public void onBlueToothAdminPermission(boolean granted){

    }
    public void showRequestResonForBtAdmin(){

    }
    public void showRequestResonForBt(){

    }
	/**
	 * 设置透明状态栏
	 */
	private void setNavigationTrans() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
			// 透明状态栏 
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); 
			}
	}
	/**
	 * 设置布局文件
	 */
	public abstract void setMyContentView();
	/**
	 * 获取Intent传递来的Data
	 */
	public void getIntentData() {};
	
	/**
	 * 初始化view之前做的操作
	 */
	public void beforeView() {}
	/**
	 * 初始化View
	 */
	public void initView(){};
	
	/**
	 * 初始化参数
	 */
	public void initData(){};
	
	/**
	 * 
	 * 是否设置Activity全屏显示
	 * 默认全屏，若某界面想设置非全屏则需要调用设置setFullscreen(false)
	 * @param isFullscreen
	 */
	public void setFullscreen(boolean isFullscreen){
		if(isFullscreen){
			//全屏
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}else{
			//非全屏（默认模式）
			this.requestWindowFeature(Window.FEATURE_ACTION_BAR);
			this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
	}
	
	/**
	 * 隐藏底部Navigation
	 */
	private void hiddenNavigation(){

		getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
				|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE); 
	}
	
	 /**
     * 显示请求服务器Dialog
     */
    public void showDialog(String message) {
        dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        dialog.setMessage(message);
        if(!dialog.isShowing())
        dialog.show();
    }

    /**
     * 显示请求服务器Dialog
     */
    public void showDialog() {
        dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        dialog.setMessage(this.getString(R.string.msg_common_i_wait));
        if(!dialog.isShowing())
        	dialog.show();
    }

    /**
     * 关闭请求服务器Dialog
     */
    public void disMissDialog() {
        if (ObjectUtils.isNotEmpty(dialog)) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }
    
    
    @Override
    protected void onStart() {
    	super.onStart();
    	MyLog.d(TAG, "onStart");
    }
    
    @Override
    protected void onRestart() {
    	super.onRestart();
    	MyLog.d(TAG, "onRestart");
    }
 
    @Override
    protected void onNewIntent(Intent intent) {
    	super.onNewIntent(intent);
    	MyLog.d(TAG, "onNewIntent");
    }
    
	@Override
	protected void onResume() {
		super.onResume();
		MyLog.d(TAG, "onResume");
		MyLog.d(TAG, "mPageName : " + mPageName);
		//因为MainActivity中依附有Fragment则在MainActivity只中统计时长，在Fragment只中统计跳转
		if(!mPageName.equals(Constant.CLASS_NAME_MAIN)){
			MobclickAgent.onPageStart(mPageName);	
		}
		MobclickAgent.onResume(this);
		
	//	getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(mOnSystemUiVisibilityChangeListener);
		
	//	hiddenNavigation();
	}
	
	
	@Override
	protected void onPause() {
		super.onPause();
		MyLog.d(TAG, "onPause");
		if(!mPageName.equals(Constant.CLASS_NAME_MAIN)){
			MobclickAgent.onPageEnd(mPageName);
		}
        MobclickAgent.onPause(this);
        
	//	getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(null);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		MyLog.d(TAG, "onStop");
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MyLog.d(TAG, "onDestroy");
	}
	
	
	private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener = new OnSystemUiVisibilityChangeListener() {
		
		@Override
		public void onSystemUiVisibilityChange(int visibility) {
			
			MyLog.e(TAG, "onSystemUiVisibilityChange:"+visibility);
			
			
			
			if(visibility==0){
				
				mHandeler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						
						hiddenNavigation();
						
					}
				}, delay);
				
			}
			 
			
		}
	};
}
